package com.ve.downloader.utils;

import com.ve.downloader.queue.FixQueue;
import com.ve.downloader.queue.QuickFixQueue;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;

public class FUtils {
    public static byte[] file2byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            System.out.println("reading : " + fis.available());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[2048];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public static byte[] getFixBin(String path) {
        return getFixBin(file2byte(path));

    }
    public static byte[] getFixBin(byte[] data) {

        byte[] CHECK = new byte[5];
        Arrays.fill(CHECK, (byte) 0xff);
        FixQueue queue = new QuickFixQueue(CHECK.length);
        int index = 0;
        for (int i = 0; i < data.length; i++) {
            queue.push(data[i]);
            if (queue.equalsArray(CHECK)) {
                index = i;
                break;
            }
        }
        if (index == 0) {
            return data;
        }
        return Arrays.copyOfRange(data, 0, index - CHECK.length);

    }
}
